import ApiPageList from "@/api/ApiV1WxContactPageList_post"; // TAV
import { Toast } from "@/hooks/Providers";
import { useLocalForageItem } from "@/hooks/useLocalForage";
import { contact_adapter2, IContactItem } from "@/mgr";
import { usePaging } from "@/utils/usePaging";
import { ContactEditModal } from "@/views/ContactEditView";
import { LoadingOutlined, UserAddOutlined } from "@ant-design/icons";
import { Button, Dropdown, Typography } from "antd";
import { useCallback } from "react";
import { useImmer } from "use-immer";
import { FlexHeader, FlexRoot, ListEmpty } from "../../_BaseView/FlexRoot";
import { List } from "../../_BaseView/List";
import { ContactItem } from "../../ContactsView/ContactItem";
import { InputSearch } from "@/component/InputSearch";
export interface IUIItem extends ApiPageList.RespData { }

export default function ContactManagement() {
  const [toast] = Toast.use()
  const [filters, set_filters, filters_ready] = useLocalForageItem<ApiPageList.BodyParams>({
    key: `${ContactManagement.name}#filters`
  });

  const { paging, list, set_list, total } = usePaging<IContactItem, ApiPageList.BodyParams>({
    forage_key: `${ContactManagement.name}#list`,
    ready: filters_ready,
    catcher: e => { toast.error(e) },
    loader: async (p) => {
      const body: ApiPageList.BodyParams = {
        ...p.params,
        pageNo: p.page,
        pageSize: p.page_size
      }
      const start_idx = ((p.page - 1) * p.page_size)
      const reply = await ApiPageList.call(body);
      const raws: IUIItem[] = (reply as any).data ?? []
      const total = (reply as any).totalCount ?? raws.length ?? 0
      p.set_total(total)
      return raws.map((v, i) => {
        const ret = contact_adapter2(v)
        const index = (1 + start_idx + i)
        ret.index = index
        return ret
      });
    }
  })

  const [editing_item, set_editing_item] = useImmer<{ open?: boolean, data?: IContactItem }>({});
  const render_item = useCallback((item: IContactItem) => {
    const edit = () => set_editing_item({ open: true, data: item })
    return (
      <Dropdown
        trigger={['contextMenu']}
        menu={{ items: [{ key: '_', label: '修改信息', onClick: () => set_editing_item({ open: true, data: item }) }] }}>
        <ContactItem
          show_account item={item}
          key={item.userName}
          searching_value={filters?.searchContent}
          actions={({ item: { phone }, loading, }) => <>
            {
              phone ? null :
                <Button shape='circle' disabled={loading} type='text' size='small' onClick={edit} title='设置联系人信息'>
                  {loading ? <LoadingOutlined /> : <UserAddOutlined />}
                </Button >
            }
          </>} />
      </Dropdown >
    )
  }, [filters?.searchContent, ContactItem])

  const load_more = () => paging.load()
  const refresh = () => paging.load(true, filters)
  return (
    <FlexRoot vertical>
      <FlexHeader vertical align='stretch'>
        <InputSearch
          value={filters?.searchContent ?? ''}
          onChange={e => set_filters(o => ({ ...o, searchContent: e.target.value }))}
          loading={paging.loading}
          style={{ flex: 1, paddingLeft: 0, paddingRight: 0 }}
          placeholder="账号/群名/发送人"
          allowClear
          onSearch={refresh} />
        <Typography.Text type='secondary'>共有{paging.total}个联系人</Typography.Text>
      </FlexHeader>
      <List
        virtual={Number(list?.length) > 100}
        data={list || []}
        itemHeight={71}
        itemKey={i => `${i.account}_${i.userName}`}
        on_reach_end={load_more}
        others={<ListEmpty show={!total && !paging.loading} description='' />}>
        {render_item}
      </List>
      <ContactEditModal
        open={editing_item.open}
        onCancel={() => set_editing_item(o => { o.open = false })}
        afterClose={() => set_editing_item(o => { o.data = void 0 })}
        data={editing_item.data}
        on_success={(edited) => {
          set_editing_item(o => { o.open = false })
          set_list(o => {
            if (!o) return o;
            const ret = [...o];
            const index = ret.findIndex(a => a.account === edited.account && a.userName === edited.userName)
            if (index >= 0) ret[index] = edited;
            return ret;
          })
        }} />
    </FlexRoot>
  )
}
